package com.ruoyi.common.utils.sign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Random;

/**
 * @author ：jijinwu
 * @ClassName WxDecryptUtil
 * @date ：2024/7/17 - 17:26
 * @version: V1.0
 * @slogan: 天下风云出我辈，一入代码岁月催
 * @description: 微信加密数据解密工具类
 **/
public class WxDecryptUtil {
    private static final Logger log = LoggerFactory.getLogger(WxDecryptUtil.class);
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private byte[] sessionKey;

    public WxDecryptUtil() {
    }

    /**
     * 微信加密数据解密
     * @param iv 加密向量iv
     * @param encryptedData 加密数据
     * @return
     */
    public String decryptWXData(String iv,String encryptedData,String sessionKey)  {
        try {
            this.sessionKey = Base64.getDecoder().decode(sessionKey);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            SecretKeySpec secretKey = new SecretKeySpec(this.sessionKey, "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(Base64.getDecoder().decode(iv));
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
            byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
            return new String(decryptedData, "UTF-8");
        } catch (Exception e) {
            log.error("解密微信加密数据失败:",e.getMessage());
            return null;
        }
    }
}

